#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证相关路由
"""
import secrets
from datetime import datetime, timedelta
from fastapi import APIRouter, Request, Form, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates

from ..database import get_db_connection
from ..utils.security import hash_password
from ..utils.email import send_email
from .session import get_current_user, create_session, delete_session
from modules.utils.config import config

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/", response_class=HTMLResponse)
async def index(request: Request):
    """首页"""
    user = get_current_user(request)
    if user:
        if user['role'] == 'admin':
            return RedirectResponse(url="/admin", status_code=302)
        else:
            return RedirectResponse(url="/passwords", status_code=302)
    else:
        return templates.TemplateResponse("index.html", {
            "request": request,
            "user": None,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full')
        })


@router.get("/home", response_class=HTMLResponse)
async def home(request: Request):
    """用户首页"""
    user = get_current_user(request)
    return templates.TemplateResponse("index.html", {
        "request": request,
        "user": user,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """登录页面"""
    return templates.TemplateResponse("login.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.post("/login")
async def login(request: Request, username: str = Form(...), password: str = Form(...)):
    """用户登录"""
    conn = get_db_connection()
    
    # 查找用户
    user = conn.execute(
        "SELECT * FROM users WHERE username = ? AND is_active = 1", 
        (username,)
    ).fetchone()
    
    if not user or user['password_hash'] != hash_password(password):
        conn.close()
        return templates.TemplateResponse("login.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full'),
            "error": "用户名或密码错误"
        })
    
    conn.close()
    
    # 创建会话
    session_token = create_session(user['id'])
    
    
    
    # 设置cookie并重定向
    if user['role'] == 'admin':
        response = RedirectResponse(url="/admin", status_code=302)
    else:
        response = RedirectResponse(url="/passwords", status_code=302)
    
    response.set_cookie(
        key="session_token",
        value=session_token,
        max_age=7*24*60*60,  # 7天
        httponly=True,
        secure=False  # 在生产环境中应设为True
    )
    
    return response


@router.get("/register", response_class=HTMLResponse)
async def register_page(request: Request):
    """注册页面"""
    return templates.TemplateResponse("register.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.post("/register")
async def register(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    confirm_password: str = Form(...),
    phone: str = Form(""),
    email: str = Form(...),
    verification_code: str = Form(...)
):
    """用户注册"""
    # 验证密码确认
    if password != confirm_password:
        return templates.TemplateResponse("register.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full'),
            "error": "两次输入的密码不一致"
        })

    # 验证验证码
    conn = get_db_connection()
    verification = conn.execute(
        "SELECT * FROM email_verifications WHERE email = ? AND code = ? AND expires_at > ?",
        (email, verification_code, datetime.now())
    ).fetchone()

    if not verification:
        conn.close()
        return templates.TemplateResponse("register.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full'),
            "error": "验证码无效或已过期"
        })

    # 删除已使用的验证码
    conn.execute("DELETE FROM email_verifications WHERE id = ?", (verification['id'],))
    conn.commit()
    conn.close()
    
    conn = get_db_connection()
    
    # 检查用户名是否已存在
    existing_user = conn.execute("SELECT id FROM users WHERE username = ?", (username,)).fetchone()
    if existing_user:
        conn.close()
        return templates.TemplateResponse("register.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full'),
            "error": "用户名已存在"
        })
    
    # 创建新用户
    password_hash = hash_password(password)
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO users (username, password_hash, phone, email)
        VALUES (?, ?, ?, ?)
    """, (username, password_hash, phone, email))
    
    user_id = cursor.lastrowid
    conn.commit()
    conn.close()
    
    
    return templates.TemplateResponse("register.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full'),
        "success": "注册成功！请登录"
    })


@router.get("/logout")
async def logout(request: Request):
    """用户登出"""
    session_token = request.cookies.get("session_token")
    if session_token:
        # 删除会话
        delete_session(session_token)

    response = RedirectResponse(url="/login", status_code=302)
    response.delete_cookie("session_token")
    return response


@router.get("/service-agreement", response_class=HTMLResponse)
async def service_agreement(request: Request):
    """服务协议页面"""
    return templates.TemplateResponse("service_agreement.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.get("/privacy-policy", response_class=HTMLResponse)
async def privacy_policy(request: Request):
    """隐私政策页面"""
    return templates.TemplateResponse("privacy_policy.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.get("/forgot-password", response_class=HTMLResponse)
async def forgot_password_page(request: Request):
    """忘记密码页面"""
    return templates.TemplateResponse("forgot_password.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full')
    })


@router.post("/send-verification-code")
async def send_verification_code(email: str = Form(...)):
    """发送邮箱验证码"""
    # 生成6位数验证码
    verification_code = ''.join(secrets.choice('0123456789') for _ in range(6))
    expires_at = datetime.now() + timedelta(minutes=10)

    conn = get_db_connection()
    cursor = conn.cursor()

    # 检查是否已有该邮箱的验证码，如果有则更新
    existing = conn.execute("SELECT id FROM email_verifications WHERE email = ?", (email,)).fetchone()
    if existing:
        cursor.execute(
            "UPDATE email_verifications SET code = ?, expires_at = ? WHERE email = ?",
            (verification_code, expires_at, email)
        )
    else:
        # 如果没有则插入新记录
        cursor.execute(
            "INSERT INTO email_verifications (email, code, expires_at) VALUES (?, ?, ?)",
            (email, verification_code, expires_at)
        )

    conn.commit()
    conn.close()

    # 发送邮件
    subject = "注册验证码"
    body = f"您的注册验证码是: {verification_code}，有效期10分钟。请勿泄露给他人。"
    try:
        send_email(email, subject, body)
        return JSONResponse(content={"detail": "验证码已发送"})
    except Exception as e:
        return JSONResponse(content={"detail": f"发送失败: {str(e)}"}, status_code=500)


@router.post("/forgot-password")
async def forgot_password(request: Request, email: str = Form(...)):
    """处理忘记密码请求"""
    conn = get_db_connection()
    
    # 查找用户
    user = conn.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()
    if not user:
        conn.close()
        return templates.TemplateResponse("forgot_password.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_full'),
            "error": "邮箱地址不存在"
        })
    
    # 生成重置令牌和验证码
    code = secrets.token_hex(3)  # 生成6位十六进制验证码
    expires_at = datetime.now() + timedelta(hours=1)  # 1小时后过期

    # 删除旧的验证码
    cursor = conn.cursor()
    cursor.execute("DELETE FROM email_verifications WHERE email = ?", (email,))

    # 插入新的验证码
    cursor.execute("""
        INSERT INTO email_verifications (email, code, expires_at)
        VALUES (?, ?, ?)
    """, (email, code, expires_at))
    
    conn.commit()
    conn.close()
    
    # 发送验证码邮件
    send_email(email, "密码重置验证码", f"您的验证码是：{code}，有效期1小时")
    
    return templates.TemplateResponse("forgot_password.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full'),
        "success": "验证码已发送到您的邮箱"
    })


@router.post("/resend-code")
async def resend_code(request: Request, email: str = Form(...)):
    """重新发送验证码"""
    conn = get_db_connection()
    port = config.get('DEFAULT', 'web_port')
    
    # 查找用户
    user = conn.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()
    if not user:
        conn.close()
        return JSONResponse(
            status_code=400,
            content={"detail": "邮箱地址不存在"}
        )
    
    # 生成新的验证码
    code = secrets.token_hex(3)  # 生成6位十六进制验证码
    expires_at = datetime.now() + timedelta(hours=1)  # 1小时后过期

    # 更新现有的重置记录
    cursor = conn.cursor()
    cursor.execute("""
        UPDATE email_verifications
        SET code = ?, expires_at = ?
        WHERE email = ?
    """, (code, expires_at, email))
    
    # 如果没有现有记录，则创建新记录
    if cursor.rowcount == 0:
        reset_token = secrets.token_urlsafe(32)
        cursor.execute("""
            INSERT INTO email_verifications (email, token, code, expires_at)
            VALUES (?,?, ?)
        """, (email, reset_token, code, expires_at))
    
    conn.commit()
    conn.close()
    
    # 发送验证码邮件
    send_email(email, "密码重置验证码", f"您的验证码是：{code}，有效期1小时")
    
    return JSONResponse(
        status_code=200,
        content={"detail": "验证码已重新发送"}
    )


@router.post("/verify-code")
async def verify_code(request: Request, email: str = Form(...), code: str = Form(...)):
    """验证验证码"""
    conn = get_db_connection()
    
    # 查找有效的密码重置记录
    reset_record = conn.execute("""
        SELECT * FROM email_verifications 
        WHERE email = ? AND code = ? AND expires_at > datetime('now')
    """, (email, code)).fetchone()
    
    conn.close()
    
    if not reset_record:
        return JSONResponse(
            status_code=400,
            content={"detail": "验证码无效或已过期"}
        )
    
    # 验证码验证通过，返回成功响应
    return JSONResponse(
        status_code=200,
        content={
            "detail": "验证码验证成功",
            "reset_token": reset_record['code']
        }
    )


@router.post("/reset-password")
async def reset_password_post(
    request: Request,
    code: str = Form(...),
    new_password: str = Form(...),
    confirm_password: str = Form(...)
):
    """重置密码"""
    if new_password != confirm_password:
        return templates.TemplateResponse("forgot_password.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "error": "两次输入的密码不一致",
            "show_reset_form": True,
            "code": code
        })

    conn = get_db_connection()

    # 验证重置令牌
    reset_record = conn.execute("""
        SELECT pr.*, u.id as user_id FROM email_verifications pr
        JOIN users u ON pr.email = u.email
        WHERE pr.code = ? AND pr.expires_at > datetime('now')
    """, (code,)).fetchone()

    if not reset_record:
        conn.close()
        return templates.TemplateResponse("forgot_password.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "error": "重置链接无效或已过期"
        })

    # 更新密码
    new_password_hash = hash_password(new_password)
    cursor = conn.cursor()
    cursor.execute("""
        UPDATE users SET password_hash = ?, updated_at = ?
        WHERE id = ?
    """, (new_password_hash, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), reset_record['user_id']))

    # 删除重置令牌
    cursor.execute("DELETE FROM email_verifications WHERE code = ?", (code,))

    conn.commit()
    conn.close()

    return templates.TemplateResponse("forgot_password.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "success": "密码重置成功！请使用新密码登录"
    })